<template>
  <div class="container">
    <span :style="{ color: textColor }">{{ computedIndicate.toFixed(precision) }}</span>
    <span style="color: rgb(173, 233, 246)">{{ params }}</span>
    <span :style="{ color: textColor }">{{ computedIndicate.toFixed(precision) }}</span>
  </div>
</template>

<script setup>
import { ref, defineProps, watch, onMounted } from 'vue'

const EPSILON = 1e-10 // 0.0000000001标识精度
let current = 0
let target = 0
const textColor = ref('white')

// 定义props，传入indicate，默认值为0
const props = defineProps({
  indicate: {
    //指示
    type: Number,
    default: 0
  },
  speed: {
    //速度变化
    type: Number,
    default: 200
  },
  params: {
    //显示的参数值
    type: String
  },
  warningLine: {
    //参数超过多少会有红色警告
    type: Number
  },
  precision: {
    //精度，显示小数点后几位
    type: Number,
    default: 1
  }
})

const computedIndicate = ref(0)

onMounted(() => {
  computedIndicate.value = props.indicate
})

// 监听indicate的变化
watch(
  () => props.indicate,
  (newVal, oldVal) => {
    if (newVal != oldVal) {
      target = newVal
    }
    computeVal()
  }
)

const computeVal = () => {
  let step = (target - current) / props.speed
  if (step > 0.2) {
    step = 0.2
  }
  if (step < -0.2) {
    step = -0.2
  }
  // 如果角度差值很小，停止动画
  if (Math.abs(step) < EPSILON) {
    current = target
    return
  }
  current += step
  computedIndicate.value = current

  if (computedIndicate.value >= props.warningLine - 1) {
    textColor.value = 'red'
  } else {
    textColor.value = 'white'
  }
  requestAnimationFrame(() => computeVal())
}
</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-between;
  width: 170px;
  align-items: center;
  margin-left: 40px;
  margin-top: -5px;
}
</style>
